// miniprogram/pages/app1/app1.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    appointment: [],
    page: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    db.collection('appointment').where({
      status: ('已完成')
    }).orderBy('time', 'desc').get({
      success: res => {
        this.setData({
          appointment: res.data
        })
        this.jishu()
      },
      fail: err => {
        wx.showToast({
          icon: "none",
          title: '查询记录失败',
        })
      }
    })
  },
  tiao: function(e) {
    wx.navigateTo({
      url: '../appointment-1/appointment-1?id=' + e.currentTarget.dataset.id
    })
    // console.log(e)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  jishu: function() {
    let that = this
    // wx.cloud.callFunction({
    //   name: 'count',
      // success: function(res) {
      //   that.data.all = res.result.total
      // }
    // })
    db.collection('appointment').where({
      status:'已完成'
    }).count({
      success: res => {
        console.log(res)
        that.data.all = res.total
      }
    })
  },
  onShow: function() {
    // if (this.data.page) {
    //   this.jiazai();
    // }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading()
    this.onLoad()
    wx.hideNavigationBarLoading();
  },
  load: function() {
    let that = this
    let shu = 20
    let dir = this.data.appointment
    that.data.page = that.data.page + 20
    const db = wx.cloud.database()
    db.collection('appointment').orderBy('time', 'desc').skip(this.data.page).limit(shu).get({
      success: res => {
        dir = dir.concat(res.data)
        this.data.appointment = dir
        this.setData({
          appointment: this.data.appointment
        })
      },
      fail: err => {
        wx.showToast({
          icon: "none",
          title: '到底了哦~',
        })
      }
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  // onReachBottom: function() {
  //   wx.showNavigationBarLoading()
  //   wx.hideNavigationBarLoading();
  //   wx.showToast({
  //     icon: "none",
  //     title: '已经到底了',
  //   })
  // }
  onReachBottom: function() {
    console.log(this.data.page)
    console.log(this.data.all)
    if (this.data.page <= this.data.all) {
      wx.hideNavigationBarLoading(); //隐藏加载
      wx.stopPullDownRefresh();
      this.load()
    } else {

    }
  }
})